#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

#include "Stack.h"

void StackInit(Stack* ps)
{
    assert(ps);

    ps->array = (DataType*)malloc(sizeof(DataType)*3); //数组开辟空间
    if(NULL == ps->array)
    {
        assert(0);
        return;
    }

    ps->capacity = 3;
    ps->size = 0;
}

void CheckCapacity(Stack* ps)
{
    assert(ps);

    if(ps->size == ps->capacity)
    {
        ps->array = (DataType*)realloc(ps->array, sizeof(DataType) * ps->capacity*2); 
        if(NULL == ps->array)
        {
            assert(0);
            return;
        }

        ps->capacity *= 2; //空间修改成功后，需要对容量改写
    }
}

//入栈
void StackPush(Stack* ps, DataType data)
{
    assert(ps);

    //扩容
    CheckCapacity(ps);

    ps->array[ps->size++] = data;
}

//出栈
void StackPop(Stack* ps)
{
    assert(ps);

    if(StackEmpty(ps)) //判空
        return;
    
    ps->size--;
}

//获取栈顶元素
DataType StackTop(Stack* ps)
{
    assert(ps && !StackEmpty(ps));
    //不能用if判断是否是空的，从空的栈里获取元素是非法的，if只能判断合法的情况
    
    return ps->array[ps->size-1];
}

//有效元素的大小
int StackSize(Stack* ps)
{
    assert(ps);

    return ps->size;
}

//判空
int StackEmpty(Stack* ps)
{
    assert(ps);

    return 0 == ps->size;
}

//销毁
void StackDestroy(Stack* ps)
{
    assert(ps);

    if(ps->array)
    {
        free(ps->array);
        ps->array = NULL;
        ps->capacity = 0;
        ps->size = 0;
    }
}

